package com.hphs.advice;

import cn.hutool.json.JSONUtil;
import com.hphs.dto.ResponseDTO;
import com.hphs.exception.MyException;
import com.hphs.info.PageInfo;
import com.hphs.utils.LocalPageInfoutil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@RestControllerAdvice  //增强器
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
   //增强器的开口
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //支持所有的接口
        return true;
    }

    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof MyException){
            MyException myException= (MyException) ex;
          return ResponseDTO.error(myException.getCode(), ex.getMessage());
        }
        return ResponseDTO.error(99,ex.getMessage());
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        //双层嵌套
        if(body instanceof  ResponseDTO){
            return body;
        }

        ResponseDTO dto=ResponseDTO.success(body);
        //解决string字符串的返回消息
        if(aClass== StringHttpMessageConverter.class){
            //改成json字符
            return JSONUtil.toJsonStr(dto);
        }
        //如果线程上有分页的信息
        PageInfo pageInfo= LocalPageInfoutil.get();
        if (pageInfo != null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("item",body);
            dto=ResponseDTO.success(map);
            //一定要记得删除
            LocalPageInfoutil.remove();
        }


        return dto;
    }
}
